package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysUserService;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String uuid)
    {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        // if (captcha == null)
        // {
        //     AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
        //     throw new CaptchaExpireException();
        // }
        // if (!code.equalsIgnoreCase(captcha))
        // {
        //     AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
        //     throw new CaptchaException();
        // }
        //验证当前用户是否是冻结状态、密码是否超过三个月没有更新
//        SysUser user = userService.selectUserByUserName(username);
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            //设置登录失败次数
            setLoginFailTimes(username);
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser user = loginUser.getUser();
        //验证是否冻结
//            if (StrUtil.equals(user.getStatus(),"2")){
//                throw new CustomException("该用户已被冻结，请联系管理员解冻");
//            }
        //验证密码是否超过三个月没更新
        if(!username.equals("admin")){
            Date nowDate = new Date();
            DateTime dateTime = DateUtil.offsetMonth(nowDate, -3);
            Date passwordTime = null;
            if (user.getPasswordTime() == null){
                passwordTime = user.getCreateTime();
            }else {
                passwordTime = user.getPasswordTime();
            }
            if (dateTime.compareTo(passwordTime) >= 0){
                throw new CustomException("当前密码使用超过三个月，请重置密码后再登录");
            }
        }

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(loginUser.getUser());
        //清除登录失败缓存
        redisCache.deleteObject(username + "LOGIN_FAIL_TIMES");
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录用户登录失败次数
     *
     * @param username
     */
    private void setLoginFailTimes(String username){
        if(username.equals("admin"))return;
        int times = redisCache.getCacheObject(username + "LOGIN_FAIL_TIMES") == null ? 1 : (int) redisCache.getCacheObject(username + "LOGIN_FAIL_TIMES");
        if (times == 5){
            //超过五次冻结账户，并清除缓存
            userService.setUserStatus(username,"1");
            redisCache.deleteObject(username + "LOGIN_FAIL_TIMES");
            return;
        }
        times ++;
        //设置三天过期时间
        redisCache.setCacheObject(username + "LOGIN_FAIL_TIMES",times,3, TimeUnit.DAYS);
    }

    /**
     * 用户重置密码
     * @param username
     * @param oldPassword
     * @param newPassword
     * @return
     */
    public boolean resetPwd(String username, String oldPassword, String newPassword){
        if (StrUtil.isBlank(newPassword) || !newPassword.matches("^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,16}$")){
            throw new CustomException("密码必须由大小写字母、数字、特殊符号的8-16位组成");
        }
        if (StrUtil.equals(oldPassword,newPassword)){
            throw new CustomException("新密码不能与旧密码相同");
        }
        SysUser user = userService.selectUserByUserName(username);
        if (user == null){
            throw new CustomException("用户名或密码错误");
        }
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)){
            throw new CustomException("用户名或密码错误");
        }
        //修改密码
        return userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0;
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(SysUser user)
    {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(user);
    }
}
